<?php

class Form_Project extends QForm
{
    /**
     * 创建 Form_Project 表单对象
     *
     * @param string $action
     * @param string $status
     *
     * @return Form_Project
     */
    static function createForm($action, $status = 'create')
    {
        $form = self::_createFromConfig($action, 'project_form.yaml');
        if ($status == 'edit')
        {
            // 如果是编辑状态，则加入额外的元素和上传子表单
            $form->add(QForm::ELEMENT, 'is_pending_delete', array(
                '_ui'           => 'checkbox',
                'caption'       => '选中后提交，将删除该项目（管理员审核后才会实际删除）',
                'caption_class' => 'important',
            ));
            $form['name']->readonly = true;
        }
        return $form;
    }

    /**
     * 创建用于项目编辑的上传表单
     *
     * @param string $action
     *
     * @return Form_Upload
     */
    static function createUploadForm($action)
    {
        $types = Q::normalize(Q::ini('appini/projects/upload_allowed_types'));
        $size = intval(Q::ini('appini/projects/upload_allowed_size') * 1024);
        $filename = rtrim(dirname(__FILE__), '/\\') . DS . 'project_upload_form.yaml';

        $form = new Form_Upload('form_upload', $action);
        $form->loadFromConfig(Helper_YAML::loadCached($filename))
             ->selectUploadElement('postfile')
             ->uploadAllowedTypes($types)
             ->uploadAllowedSize($size);

        $form['postfile']->_tips = sprintf($form['postfile']->_tips, implode('/', $types), $size / 1024);
        return $form;
    }

    /**
     * 从配置文件创建表单
     *
     * @param string $action
     * @param string $config_name
     *
     * @return Form_Project
     */
    static protected function _createFromConfig($action, $config_name)
    {
        $form = new Form_Project('form_project', $action);
        $filename = rtrim(dirname(__FILE__), '/\\') . DS . $config_name;
        $form->loadFromConfig(Helper_YAML::loadCached($filename));
        $form->addValidations(Project::meta());

        $arr = ProjectCategory::find()->order('order_pos DESC')->getAll();
        $form->element('cat_id')->items = Helper_Array::toHashMap($arr, 'id', 'name');
        $form->element('formatter')->items = Q::ini('appini/site/text_formatter');
        return $form;
    }
}
